#include "pubsubclient.h"
#include "../../base/CurrentOfThread.h"
#include "../../base/ProcessInfo.h"
#include "../../net/EventLoop.h"
#include "../../net/EventLoopThread.h"
#include <iostream>
#include <stdio.h>
#include <string>

using namespace yhaida;
using namespace pubsub;

EventLoop *g_loop = NULL;
string g_topic;
string g_content;

void connection(PubSubClient *client)
{
    if (client->connected())
    {
        client->publish(g_topic, g_content);
        client->stop();
    }
    else
    {
        g_loop->quit();
    }
}

int main(int argc, char *argv[])
{

    if (argc == 4)
    {
        string hostport = argv[1];
        size_t index_port = hostport.find(':');
        if (index_port != std::string::npos)
        {
            string host = hostport.substr(0, index_port);
            uint16_t port = static_cast<uint16_t>(atoi(hostport.c_str() + index_port + 1));
            g_topic = argv[2];
            g_content = argv[3];

            std::string name = ProcessInfo::username() + "@" + ProcessInfo::hostname();
            name += ":" + ProcessInfo::pidString();

            if (g_content == "-")
            {
                EventLoopThread loopThread;
                g_loop = loopThread.startLoop();
                PubSubClient _client(g_loop, InetAddress(host, port));
                _client.start();

                std::string line;
                while (getline(std::cin, line))
                {
                    _client.publish(g_topic, line);
                }
                _client.stop();
                yhaida::CurrentOfThread::sleepUsec(1000 * 1000);
            }
            else
            {
                EventLoop loop;
                g_loop = &loop;
                PubSubClient client(g_loop, InetAddress(host, port));
                client.setConnectionCallback(connection);
                client.start();
                loop.loop();
            }
        }
        else
        {
            printf("Usage: %s hub_ip:port topic content\n", argv[0]);
        }
    }
    else
    {
        printf("Usage: %s hub_ip:port topic content\n"
               "Read contents from stdin:\n"
               "  %s hub_ip:port topic -\n",
               argv[0], argv[0]);
    }
}